package com.example.xy_assistant;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.xy_assistant.bean.Note;
import org.litepal.LitePal;

public class NewNoteActivity extends AppCompatActivity {

    private EditText et_title;
    private EditText et_content;
    private Note note;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_note);
        initView();
        long noteId = getIntent().getLongExtra("note", 0);

        if (noteId!=0){
            note = LitePal.find(Note.class, noteId);
            et_title.setText(this.note.getTitle());
            et_content.setText(this.note.getContent());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_new_note, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==R.id.menu_save){
            submit();
            return true;
        }
        return false;
    }

    private void initView() {
        et_title = (EditText) findViewById(R.id.et_title);
        et_content = (EditText) findViewById(R.id.et_content);
    }

    private void submit() {
        // validate
        String title = et_title.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String content = et_content.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (note==null) {
            note = new Note(title, content, System.currentTimeMillis());
        }else {
            note.setTitle(title);
            note.setContent(content);
        }
        note.save();
    }
}